import {
  Controller,
  Post,
  UseInterceptors,
  UploadedFile,
  Res,
  Get,
  Param,
} from '@nestjs/common';
import { FileManageService } from './file-manage.service';
import { FileInterceptor } from '@nestjs/platform-express';
import { join } from 'path';

@Controller()
export class FileManageController {
  constructor(private readonly fileManageService: FileManageService) {}

  @Post()
  @UseInterceptors(FileInterceptor('file'))
  async upload(@UploadedFile() file: Express.Multer.File, @Res() res) {
    const fileName = await this.fileManageService.computeMd5(file.path);
    const url = new URL(
      `http://${process.env.IP}:${process.env.PORT}${process.env.PREFIX}/${fileName}`,
    );
    res.send({
      code: 0,
      msg: '上传成功',
      data: {
        fileName,
        img_url: url.href,
      },
    });
  }

  @Get(':fileName')
  download(@Res() res, @Param('fileName') fileName) {
    const url =
      process.env.STORAGE_ADDRESS ||
      join(__dirname, `../../../fileStorage/${fileName}`);
    res.download(url);
  }
}
